package com.yc.mypredictefactory;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

/**
 * 自定义路由断言工厂，用于根据请求的Accept-Language头信息转发到不同语言服务
 * 	Header:  添加 Accept-Language: zh | en |  ja
 */
@Component
public class LanguageRoutePredicateFactory extends AbstractRoutePredicateFactory<LanguageRoutePredicateFactory.Config> {

    public LanguageRoutePredicateFactory() {
        super(Config.class);
    }

    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList("language");
    }

    @Override
    public Predicate<ServerWebExchange> apply(Config config) {
        return exchange -> {
            // 从请求头中获取Accept-Language信息
            String acceptLanguage = exchange.getRequest().getHeaders().getFirst("Accept-Language");
            if (acceptLanguage == null) {
                return false;
            }
            // 简单匹配语言代码（例如 zh, en, ja）
            return acceptLanguage.toLowerCase().startsWith(config.getLanguage().toLowerCase());
        };
    }

    /**
     * 配置类，用于接收配置文件中的参数
     */
    public static class Config {
        private String language; // 如zh、en、ja等

        public String getLanguage() {
            return language;
        }

        public void setLanguage(String language) {
            this.language = language;
        }
    }
}